# -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 21:55:06 2017

@author: guobing
@email:glacity@126.com
"""

#encoding:utf-8
import os
import sys
import string, shutil 
import re

print("文件改名程序")
dirName=r'G:\图纸\土建\NNN+201689830404++_051511J03-001_A_A4_'
files = os.listdir(dirName) #路径可以自己
for name in files:
    originalName = name
    print("原文件名:",name) #打印出来
    a = os.path.splitext(name)#Split函数将扩展命分割开.
    #p0 = r"NNN"
    #pattern0 = re.compile(p0)#我们在编译这段正则表达式
    #matcher0 = re.match(pattern0,a[0])#在源文本中搜索符合正则表达式的部分
    #if a[1] == '.zip' and matcher0 != 'None' : 
    #print("是不是文件夹:",os.path.isdir(name)) #打印出来
    if a[1] == '.zip' and os.path.isdir(name) == 0:
        p1 = r"(\d\d\d\d\d\d[A-Z]\d\d)"
        pattern1 = re.compile(p1)#我们在编译这段正则表达式
        matcher1 = re.search(pattern1,a[0])#在源文本中搜索符合正则表达式的部分
        if matcher1 != 'None':
            NewName=matcher1.group(1)+'.zip'
            print("zip新文件名:",NewName) #打印出来
            if name != NewName and os.path.exists(dirName+os.sep+NewName)==0:
                print("name:"+dirName+os.sep+name)
                print("NewName:"+dirName+os.sep+NewName)
                os.rename(dirName+os.sep+name,dirName+os.sep+NewName)
    else:
        p2 = r"(\d\d\d\d\d\d[A-Z]\d\d\-\S+)"
        pattern2 = re.compile(p2)#我们在编译这段正则表达式
        matcher2 = re.search(pattern2,a[0])#在源文本中搜索符合正则表达式的部分
        #print("是否匹配成功:",matcher2) 
        if matcher2 != None and os.path.isdir(name) == 0:
            NewName=matcher2.group(1)+a[1]
            print("其他---新文件名:",NewName) #打印出
            if name != NewName and os.path.exists(dirName+os.sep+NewName)==0:
                print("name:"+dirName+os.sep+name)
                print("NewName:"+dirName+os.sep+NewName)
                os.rename(dirName+os.sep+ name,dirName+os.sep+NewName)
                
      
        
